﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace xycn.common
{
    /// <summary>
    /// 通用配置库，通过本类可以方便获取程序配置项的值
    /// 文件功能描述：公共类，系统配置，通过本类可以快速地访问Web.config及App.Config中的配置项
    /// 依赖说明：无依赖
    /// 异常处理：本类捕获并处理异常，当配置项不存在时，获取该类型的默认值
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 
        /// </summary>
        public static IConfiguration Configuration;
        private static ConcurrentDictionary<string, object> _cacheDic;

        /// <summary>
        /// 查询配置，返回值
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>不会捕获异常</returns>
        public static object GetConfigValue(string key)
        {
            Configuration = null;
            _cacheDic = new ConcurrentDictionary<string, object>();
            try
            {
                Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile("appsettings." + Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") + ".json", optional: true, reloadOnChange: true).Build();
                ChangeToken.OnChange(() => Configuration.GetReloadToken(), delegate
                {
                    if (_cacheDic.Any())
                    {
                        _cacheDic = new ConcurrentDictionary<string, object>();
                    }
                });
            }
            catch (Exception ex)
            {
                Configuration = null;
                return ex.Message;
            }

            if (Configuration == null)
            {
                return string.Empty;
            }

            var keyary = key.Split(':');
            if (keyary.Length == 2)
            {
                return Configuration.GetSection(keyary[0]).GetSection(keyary[1]).Value;
            }
            else
            {
                return Configuration.GetSection(key).Value;
            }
        }

        /// <summary>
        /// 查询配置，返回字符串
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>捕获异常,当未设置key时,返回空字符串</returns>
        public static string GetConfigToString(string key)
        {
            try
            {
                var obj = GetConfigValue(key);
                if (obj != null)
                {
                    return obj.ToString();
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 查询配置，返回整数
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>捕获异常,当未设置key 或key不是数字 时,返回 int 最小值</returns>
        public static int GetConfigToInt(string key)
        {
            object obj = GetConfigValue(key);
            if (obj == null)
            {
                return int.MinValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt32(obj);
                }
                catch
                {
                    return int.MinValue;
                }

            }
        }

        /// <summary>
        /// 查询配置，返回长整数
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>不会捕获异常,当未设置key 或key不是数字 时,返回 长整数 最小值</returns>
        public static long GetConfigToLong(string key)
        {
            object obj = GetConfigValue(key);
            if (obj == null)
            {
                return long.MinValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt64(obj);
                }
                catch
                {
                    return long.MinValue;
                }

            }
        }

        /// <summary>
        /// 查询配置，返回日期
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>不会捕获异常</returns>
        public static DateTime GetConfigToDateTime(string key)
        {
            object obj = GetConfigValue(key);

            if (obj == null)
            {
                return DateTime.MinValue;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(GetConfigValue(key));
                }
                catch (Exception)
                {
                    return DateTime.MinValue;
                }
            }
        }

        /// <summary>
        /// 查询配置，返回逻布尔值
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>不会捕获异常</returns>
        public static bool GetConfigToBool(string key)
        {
            object obj = GetConfigValue(key);
            if (obj == null)
            {
                return false;
            }
            else
            {
                try
                {
                    return Convert.ToBoolean(GetConfigValue(key));
                }
                catch
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 应用程序当前目录 包含最后一个目录分隔符号
        /// </summary>
        public static string BaseDirectory
        {
            get
            {
                string path = System.AppDomain.CurrentDomain.BaseDirectory;
                if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                {
                    path += System.IO.Path.DirectorySeparatorChar.ToString();
                }
                return path;
            }
        }

        /// <summary>
        /// 临时目录（当前程序下的temp子目录） 包含最后一个目录分隔符号
        /// </summary>
        public static string TempFilePath
        {
            get
            {
                string path = BaseDirectory + "temp" + System.IO.Path.DirectorySeparatorChar;
                if (!System.IO.Directory.Exists(path))
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    catch
                    {
                        return string.Empty;
                    }
                }

                return path;
            }
        }

        /// <summary>
        /// 将字符串读取出来转换成List
        /// </summary>
        /// <param name="key">配置文件Key</param>
        /// <param name="splitChar">配置文件值分隔符号 默认 逗号</param>
        /// <returns></returns>
        public static List<string> GetConfigToList(string key, string splitChar = ",")
        {
            var obj = GetConfigToString(key);

            return obj.Split(new string[] { splitChar }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

    }
}
